package com.baomidou.kisso.service.ym.impl;
import com.baomidou.kisso.common.http.HttpHelper;
import com.baomidou.kisso.common.http.HttpResult;
import com.baomidou.kisso.common.util.MD5Util;
import com.baomidou.kisso.common.util.TokenConfig;
import com.baomidou.kisso.service.ym.TokenService;
import org.apache.http.HttpRequest;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class TokenServiceImpl implements TokenService {
    public static final Logger logger = LoggerFactory.getLogger(TokenServiceImpl.class);

    @Autowired
    private TokenConfig tokenConfig;



    /**
     * 获取微服务访问的token
     *
     * @param
     * @return 微服务访问token
     */
    @Override
    public String getToken() {
        String appToken;
        try {
            Map<String, String> params = new HashMap<String, String>();
            String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
            String signature = MD5Util.md5(tokenConfig.getAppUuid() + timestamp + tokenConfig.getAppSecret());
            String url =tokenConfig.getTokenUrl();
            url=url+"?corp_uuid="+tokenConfig.getCorpUuid()+"&app_uuid="+tokenConfig.getAppUuid()+"&signature="+signature+"&timestamp="+timestamp;
            HttpResult httpResult = HttpHelper.executePost(url,params,"UTF-8",60000);
            JSONObject jsonObject = null;
            if(httpResult.getStatusCode()==200){
               jsonObject = new JSONObject(httpResult.getContent());
            }
            if (jsonObject==null||(Integer) jsonObject.get("code") != 0) {
                logger.error("获取token失败 response:" + jsonObject);
                return "";
            }
            JSONObject content = (JSONObject) jsonObject.get("content");
            appToken = content.get("accessToken").toString();
            logger.info("appToken from microService is {}", appToken);
            return appToken;
        } catch (Exception e) {
            logger.error(TokenServiceImpl.class.getName(), e);
            return null;
        }
    }

}
